package com.elitesland.org.rest;

import cn.hutool.core.util.StrUtil;
import com.elitesland.core.base.ApiCode;
import com.elitesland.core.base.ApiResult;
import com.elitesland.core.base.PagingVO;
import com.elitesland.org.param.OrgBuQParam;
import com.elitesland.org.service.OrgBuService;
import com.elitesland.org.vo.OrgBuVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/org/bus")
@Api(value = "组织结构", tags = {"BU管理"})
public class OrgBuController {

    private OrgBuService orgBuService;

    @Autowired
    public void setOrgBuService(OrgBuService orgBuService) {
        this.orgBuService = orgBuService;
    }

    @PostMapping("/byou/{ouid}")
    @ApiOperation("检索OU ID下的BU")
    public ApiResult<PagingVO<OrgBuVO>> search(
            @PathVariable Long ouid,
            @RequestBody OrgBuQParam param
    ) {
        val ret = orgBuService.searchBus(ouid, param);
        return ApiResult.ok(ret);
    }

    @PostMapping("/byou/{ouid}/tree")
    @ApiOperation("根据公司记录ID，列出下属所有BU的树状列表，可查询")
    public ApiResult<?> listBuTree(
            @PathVariable Long ouid,
            @RequestBody OrgBuQParam param
    ) {
        val buList = orgBuService.searchBuByTree(ouid, param);
        return ApiResult.ok(buList);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据记录ID返回BU")
    public ApiResult<OrgBuVO> oneById(@PathVariable Long id) {
        return orgBuService.oneById(id).map(ApiResult::ok)
                .orElse(ApiResult.fail(ApiCode.NOT_FOUND));
    }

    @PostMapping
    @ApiOperation("创建BU")
    public ApiResult<Long> create(@RequestBody OrgBuVO bu) {
        val id = orgBuService.create(bu);
        return ApiResult.ok(id);
    }

    @PutMapping
    @ApiOperation("更新BU")
    public ApiResult<Object> update(@RequestBody OrgBuVO bu) {
        orgBuService.update(bu);
        return ApiResult.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除BU")
    public ApiResult<Object> removeById(@PathVariable Long id) {
        orgBuService.removeById(id);
        return ApiResult.ok();
    }

    @PostMapping("/{id}/emplinks/{linktype}")
    @ApiOperation("将多个员工和指定BU关联")
    public ApiResult<?> addEmployeesToBu(
            @PathVariable Long id,
            @PathVariable String linktype,
            @RequestBody List<Long> employeeIds
    ) {
        orgBuService.addEmployeeLinks(id, employeeIds,
                StrUtil.isBlank(linktype) ? "" : linktype);
        return ApiResult.ok();
    }

    @PutMapping("/{id}/bindbus")
    @ApiOperation("批量把BU绑定到指定BU下, 核算中心和实体BU的绑定都支持")
    public ApiResult<?> bindBusToBu(
            @PathVariable Long id,
            @RequestBody List<Long> buIds
    ) {
        orgBuService.bindBusToBu(id, buIds);
        return ApiResult.ok();
    }
}
